package com.linkage.jz.bankruptcy.fragment.Main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.LawDetailActivity;
import com.linkage.jz.bankruptcy.adapter.LawListViewAdapter;
import com.linkage.jz.bankruptcy.bean.LawListInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.Divider;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class DateCalcDateFrgment extends Fragment  {

    //显示信息
    private TextView tv_fb,tv_stime,calc_ret;
    private RelativeLayout re_fb ,re_stime;
    private Button btn_calc,btn_reset;

    LinearLayout ll_calc_ret;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();

    private EditText item_days;
    private int type =-1;


    ArrayList<Fragment> fragments = new ArrayList<Fragment>();



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_calcdate, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    private void init(View view) {
        tv_stime = (TextView) view.findViewById(R.id.tv_stime);
        tv_fb = (TextView) view.findViewById(R.id.tv_fb);
        calc_ret = (TextView) view.findViewById(R.id.calc_ret);
        re_stime =  view.findViewById(R.id.re_stime);
        item_days = view.findViewById(R.id.item_days);
        re_fb =  view.findViewById(R.id.re_fb);
        btn_calc = (Button)view.findViewById(R.id.btn_calc);
        btn_reset = (Button)view.findViewById(R.id.btn_reset);
        ll_calc_ret = (LinearLayout) view.findViewById(R.id.ll_calc_ret);

        item_days  .addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        re_stime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(tv_stime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_stime.getText().toString());
                }

            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                setDate();
                tv_stime.setText("");
                item_days.setText("");
                tv_fb.setText("");
                type = -1;
                ll_calc_ret.setVisibility(View.GONE);
                btn_reset.setVisibility(View.GONE);
                showSave();
            }
        });

        btn_calc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    String fromDate = tv_stime.getText().toString();
                    String days = item_days.getText().toString();

                    if("".equalsIgnoreCase(fromDate)||"请选择".equalsIgnoreCase(fromDate))
                    {
                        Toast.makeText(getActivity(),"请选择时间",Toast.LENGTH_LONG).show();
                        return;
                    }
                    if("".equalsIgnoreCase(days)||"请输入".equalsIgnoreCase(fromDate))
                    {
                        Toast.makeText(getActivity(),"请设置天数",Toast.LENGTH_LONG).show();
                        return;
                    }

                    if(type==-1)
                    {
                        Toast.makeText(getActivity(),"请设置前/后",Toast.LENGTH_LONG).show();
                        return;
                    }
                    int i_days = Integer.parseInt(days);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar bef = Calendar.getInstance();

                    bef.setTime(sdf.parse(fromDate));
                    if(type ==1) {
                        bef.add(Calendar.DAY_OF_MONTH, i_days);
                    }else{
                        bef.add(Calendar.DAY_OF_MONTH, -i_days);
                    }
                    int i_year = bef.get(Calendar.YEAR);    //获取年
                    int i_month = bef.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
                    int i_day_s = bef.get(Calendar.DAY_OF_MONTH) ;
                    calc_ret.setText(i_year+"-"+i_month+"-"+i_day_s);
                    ll_calc_ret.setVisibility(View.VISIBLE);
                    btn_reset.setVisibility(View.VISIBLE);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });

        re_fb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final List<String> values = new ArrayList<String>();

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请选择");
                //    指定下拉列表的显示数据
                final String[] cities = {"前", "后"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        tv_fb.setText(cities[which]);
                        type = which;
                        showSave();
                    }
                });
                builder.show();

            }
        });
        showSave();
    }

    private void showSave()
    {

        String str1 = item_days.getText().toString();
        String str2 =  tv_stime.getText().toString().trim();
        int type3 =  type;



        if(  !str2.equalsIgnoreCase("") && !str1.equalsIgnoreCase("")
                &&  type3!=-1)



        {


            btn_calc.setClickable(true);
            btn_calc.setBackgroundResource((R.drawable.corner_btn));

        }else{
            btn_calc.setClickable(false);
            btn_calc.setBackgroundResource((R.drawable.corner_nosel_btn));
        }


    }



    public void setDate(String initdata){

        //通过自定义控件AlertDialog实现
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_dateshow, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        Calendar calendar = Calendar.getInstance();
        if("".equalsIgnoreCase(initdata)) {
            calendar.setTimeInMillis(System.currentTimeMillis());

        }else{
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date initdate = sdf.parse(initdata);
                calendar.setTime(initdate);
            }catch (Exception ex)
            {
                ex.printStackTrace();
            }

        }
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);
        //设置date布局
        builder.setView(view);
        builder.setTitle("设置日期信息");
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //日期格式
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
//                        oplandate.setText(sb);
//                        //赋值后面闹钟使用
                int mYear = datePicker.getYear();
                int mMonth = datePicker.getMonth();
                int mDay = datePicker.getDayOfMonth();

                    tv_stime.setText(sb.toString());
                showSave();
                dialog.cancel();
            }
        });
        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }


}
